package com.hinner.controller;


import cn.hutool.core.util.ObjectUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hinner.common.JwtTokenUtils;
import com.hinner.common.Result;
import com.hinner.entity.WxUser;
import com.hinner.entity.vo.WeChatSession;
import com.hinner.entity.vo.WxLoginVO;
import com.hinner.mapper.WxUserMapper;
import com.hinner.service.WxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/wx/user")
public class WxUserController {

    @Autowired
    private WxUserService wxUserService;


    @Autowired
    private WxUserMapper wxUserMapper;
    @Value("${wx.appid}")
    private String appid;
    @Value("${wx.secret}")
    private String secret;

    @PostMapping("/login")
    public Result login(@RequestBody WxLoginVO wxLoginVO) throws Exception {
        // 获取 session_key 和 openid
        String token = null;
        WeChatSession session = wxUserService.getSessionKey(wxLoginVO.getCode());
        String openId = session.getOpenid();
        String sessionKey = session.getSession_key();

        // 1.根据openId查询用户是否存在
        WxUser wxUser = wxUserService.findByOpenId(openId);
        if (ObjectUtil.isNotNull(wxUser)){
            //2. 库中已经有该用户了，直接更新下sessionKey
            wxUser.setSessionKey(sessionKey);
            wxUserService.updateById(wxUser);

        }else {
            // 3.库中没有该用户，解密用户信息并保存
            // 解密用户信息
            WxUser user = wxUserService.decryptUserInfo(wxLoginVO.getEncryptedData(), sessionKey, wxLoginVO.getIv());
            user.setSessionKey(sessionKey);
            user.setOpenId(openId);
            // 保存或更新用户信息
            wxUserService.save(user);
           // 更新引用
            wxUser = user;
        }
        token = JwtTokenUtils.genToken(wxUser.getId().toString(),wxUser.getNickName());
        return Result.success(token);
    }

    @GetMapping("/sessionKey")
    public String getSessionKey(@RequestParam("code") String code) throws JsonProcessingException {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+secret+"&js_code=" + code + "&grant_type=authorization_code";
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(url, String.class);
        WeChatSession session = new ObjectMapper().readValue(response, WeChatSession.class);
        return "openid: " + session.getOpenid() + ", session_key: " + session.getSession_key();
    }
}
